package admin

import (
	"github.com/gin-gonic/gin"
	"go-ecommerce/internal/service"
	"go-ecommerce/internal/utils"
	"go-ecommerce/internal/validate"
	"gorm.io/gorm"
	"net/http"
	"strconv"
)

// GetCategoryListHandler 分类列表接口
func GetCategoryListHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		list, err := service.GetAllCategories(db)
		if err != nil {
			utils.Error(c, http.StatusInternalServerError, "获取分类失败")
			return
		}
		utils.Success(c, list)
	}
}

// CreateCategoryHandler 创建分类接口
func CreateCategoryHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		var req validate.CreateCategoryRequest

		if err := c.ShouldBindJSON(&req); err != nil {
			utils.Error(c, http.StatusBadRequest, "参数格式错误")
			return
		}

		if err := service.CreateCategory(db, req.Name, req.Sort); err != nil {
			utils.Error(c, http.StatusInternalServerError, "创建分类失败")
			return
		}

		utils.Success(c, "创建成功")
	}
}

// UpdateCategoryHandler 更新分类接口
func UpdateCategoryHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		var req validate.UpdateCategoryRequest
		if err := c.ShouldBindJSON(&req); err != nil {
			utils.Error(c, http.StatusBadRequest, "参数错误")
			return
		}

		id, err := strconv.Atoi(c.Param("id"))
		if err != nil {
			utils.Error(c, http.StatusBadRequest, "无效的分类ID")
			return
		}

		if err := service.UpdateCategory(db, uint(id), req.Name, req.Sort); err != nil {
			utils.Error(c, http.StatusInternalServerError, "更新失败")
			return
		}

		utils.Success(c, "更新成功")
	}
}

// DeleteCategoryHandler 删除分类接口
func DeleteCategoryHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		id, err := strconv.Atoi(c.Param("id"))
		if err != nil {
			utils.Error(c, http.StatusBadRequest, "无效的分类ID")
			return
		}

		if err := service.DeleteCategory(db, uint(id)); err != nil {
			utils.Error(c, http.StatusInternalServerError, "删除失败")
			return
		}

		utils.Success(c, "删除成功")
	}
}
